<?php

namespace app\api\model;

use app\common\model\BalanceLog;
use app\common\model\BaseModel;

class Merchant extends BaseModel
{
    // 表名
    protected $name = 'merchant';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
    ];


    /**
     * 店铺收入统计.
     */
    public static function income($uid){
        //总收入
        $allMoney = BalanceLog::where(['merchant_id' => $uid])->where('type', 'in', '1,6,7')->sum('amount');
        //今日收益
        $dayMoney = BalanceLog::where(['merchant_id' => $uid])->where('type', 'in', '1,6,7')->whereDay('createtime')->sum('amount');
        //昨日收益
        $yestMoney = BalanceLog::where(['merchant_id' => $uid])->where('type', 'in', '1,6,7')->whereDay('createtime', 'yesterday')->sum('amount');
        //本月收益
        $monthMoney = BalanceLog::where(['merchant_id' => $uid])->where('type', 'in', '1,6,7')->whereMonth('createtime')->sum('amount');
        //年度收益
        $yearMoney = BalanceLog::where(['merchant_id' => $uid])->where('type', 'in', '1,6,7')->whereYear('createtime')->sum('amount');
        $income = [
            'all_money' => $allMoney,
            'day_money' => $dayMoney,
            'yest_money' => $yestMoney,
            'month_money' =>$monthMoney,
            'year_money' => $yearMoney
        ];
        return $income;
    }

    /**
     * 门店列表.
     */
    public function shopList($requestData){
        $car_id = (isset($requestData['car_id']) && !empty($requestData['car_id'])) ? $requestData['car_id'] : 0;
        $page = $requestData['page']??1;
        $limit = $requestData['limit']??10;
        $latitude = $requestData['latitude']??0;
        $longitude = $requestData['longitude']??0;
        if(!$longitude || !$latitude){
            return ['status' => 0, 'message' => '用户定位为空', 'result' => ''];
        }
        $city = $requestData['city']??'';
        if(!$city){
            return ['status' => 0, 'message' => '请选择城市', 'result' => ''];
        }
        $car_where = [['is_delete', '=', 1], ['status', '=', 1], ['examine_status', '=', 2]];
        if(in_array($city, ['北京市', '天津市', '重庆市', '上海市'])){
            $shop_where = [['is_delete', '=', 1], ['status', '=', 1], ['examine_status', '=', 2], ['province|city', '=', $city]];
        }else{
            $shop_where = [['is_delete', '=', 1], ['status', '=', 1], ['examine_status', '=', 2],  ['city', 'like', '%'.$city.'%']];
        }
        $car = null;
        if($car_id){
            $car = Car::getFind(['is_delete' => 1, 'status' => 1, 'id' => $car_id], 'id,car_name,car_image,car_site,car_gate,car_gear,drive');
            if($car){
                $car_gear = $car['car_gear'] == 1 ? '手动挡' : '自动挡';
                $car['label'] = $car['car_site'].'座|'.$car['car_gate'].'门|'.$car_gear;
                $car['drive'] = $car['drive'] . 'L';
            }
            $car_where[] = [['car_id', '=', $car_id]];
//            $car_where[] = [['brand_id', '=', $brand_id]];
//            $car_where[] = [['model_id', '=', $model_id]];
            $shop_id_list = MerchantCar::where($car_where)->column('merchant_id', 'id');
            $shop_where[] = ['id', 'in', $shop_id_list];
        }
        $shop_list = self::where($shop_where)
            ->field("id,shop_logo,shop_name,service,province,city,area,street,longitude,latitude,(6378.138 * 2 * asin(sqrt(pow(sin((latitude * pi() / 180 - " . $latitude . " * pi() / 180) / 2),2) + cos(latitude * pi() / 180) * cos(" . $latitude . " * pi() / 180) * pow(sin((longitude * pi() / 180 - " . $longitude . " * pi() / 180) / 2),2))) * 1000) as distance")
            ->order('id', 'desc')
            ->order('distance asc,createtime desc')
            ->page($page, $limit)
            ->select()->toArray();
        if($shop_list){
            foreach ($shop_list as $key=>$value){
                $merchant_car_where = $car_where;
                $shop_list[$key]['all_address'] = $value['province'].$value['city'].$value['area'].$value['street'];
                $shop_list[$key]['service_list'] = explode(',', $value['service']);
                $merchant_car_where[] = ['merchant_id', '=', $value['id']];
                $merchant_car = MerchantCar::where($merchant_car_where)->find();
                if($car_id){
                    $shop_list[$key]['merchant_car_id'] = $merchant_car['id']??0;
                    $shop_list[$key]['car_price'] = $merchant_car['car_price']??0;
                }else{
                    $shop_list[$key]['merchant_car_id'] = 0;
                    $shop_list[$key]['car_price'] = 0;
                }
            }
        }
        $list = [
            'car' => $car,
            'shop_list' => $shop_list
        ];
        return ['status' => 1, 'message' => '操作成功', 'result' => $list];
    }

    /**
     * 门店详情.
     */
    public function shopDetail($requestData){
        $merchant_id = $requestData['merchant_id']??0;
        $latitude = $requestData['latitude']??0;
        $longitude = $requestData['longitude']??0;
        if(!$longitude || !$latitude){
            return ['status' => 0, 'message' => '用户定位为空', 'result' => ''];
        }
        $merchant = self::field("id,shop_banner,shop_name,province,city,area,street,service,introduction,open_time,night_time,longitude,latitude,(6378.138 * 2 * asin(sqrt(pow(sin((latitude * pi() / 180 - " . $latitude . " * pi() / 180) / 2),2) + cos(latitude * pi() / 180) * cos(" . $latitude . " * pi() / 180) * pow(sin((longitude * pi() / 180 - " . $longitude . " * pi() / 180) / 2),2))) * 1000) as distance")
            ->where(['id' => $merchant_id, 'is_delete' => 1, 'status' => 1, 'examine_status' => 2])
            ->find();
        if(!$merchant_id || !$merchant){
            return ['status' => 0, 'message' => '门店不存在', 'result' => ''];
        }
        $merchant['all_address'] = $merchant['province'].$merchant['city'].$merchant['area'].$merchant['street'];
        $merchant['service_list'] = explode(',', $merchant['service']);
        $merchant['banner_list'] = explode(',', $merchant['shop_banner']);
        return ['status' => 1, 'message' => '操作成功', 'result' => $merchant];
    }

    /**
     * 门店车辆列表.
     */
    public function shopCarList($requestData, $user)
    {
        $merchant_id = $requestData['merchant_id']??0;
        $brand_id = $requestData['brand_id']??0;
        $model_id = $requestData['model_id']??0;
        $car_site = $requestData['car_site']??0;
        $car_gear = $requestData['car_gear']??0;
        $page = $requestData['page']??1;
        $limit = $requestData['limit']??10;
        if(!$merchant_id){
            return ['status' => 0, 'message' => '请求错误', 'result' => ''];
        }
        $merchant = self::getFind(['id' => $merchant_id, 'status' => 1, 'is_delete' => 1, 'examine_status' => 2]);
        if(!$merchant){
            return ['status' => 0, 'message' => '店铺不存在', 'result' => ''];
        }
        $where = [['merchant_id', '=', $merchant_id], ['status', '=',  1], ['is_delete', '=', 1], ['examine_status', '=', 2], ];
        //座位 档位 品牌 类型 筛选
        $car_where = ['is_delete' => 1, 'status' => 1];
        if($car_site){
            $car_where['car_site'] = $car_site;
        }
        if($car_gear){
            $car_where['car_gear'] = $car_gear;
        }
        if($brand_id){
            $car_where['brand_id'] = $brand_id;
        }
        if($model_id){
            $car_where['model_id'] = $model_id;
        }
        $car_id_list = Car::where($car_where)->column('id');
        $where[] = ['car_id', 'in', implode(',', $car_id_list)];
        $list = MerchantCar::field("id,car_id,merchant_id,merchant_car_name,car_price,car_deposit,car_label,merchant_longitude,merchant_latitude,drive,displacement")
            ->with(['carss'])
            ->where($where)
            ->order('createtime desc')
            ->page($page, $limit)
            ->select()->toArray();
        if($list){
            foreach ($list as $key=>$value){
                $car_gear = $value['car_gear'] == 1 ? '手动挡' : '自动挡';
                $label = $value['car_site'].'座|'.$value['car_gate'].'门|'.$car_gear.'|'.$value['displacement'];
                $value['car_sign'] = $label;
                if($value['car_label']){
                    $label_names = Label::where(['is_delete' => 1])->where('id', 'in', $value['car_label'])->column('name');
                    $value['car_label'] = implode(',', $label_names);
                }
                $value['car_price'] = floatval($value['car_price']);
                $value['car_deposit'] = floatval($value['car_deposit']);
                $list[$key] = $value;
            }
        }
        return ['status' => 1, 'message' => '操作成功', 'result' => $list];
    }

    /**
     * 获取列表
     * @param array $where
     * @param string $field
     * @param int $page
     * @param int $limit
     * @return Driver[]|array|\think\Collection
     */
    public static function getList($where = [], $field = '*', $order = 'createtime desc', $page = 1, $limit = 10){
        if($page){
            return self::where($where)->field($field)->order('id', 'desc')->order($order)->page($page, $limit)->select();
        }else{
            return self::where($where)->field($field)->order('id', 'desc')->select();
        }
    }

    /**
     * 获取单条
     * @param array $where
     * @param string $field
     * @return Driver|array|mixed|\think\Model|null
     */
    public static function getFind($where = [], $field = '*'){
        return self::where($where)->field($field)->find();
    }

    //服务类型
    public static function serviceList($type = null,$isFront = false){
        $data = ['1' => '到店自取', '2' => '送车上门', '3' => '免押金',];
        if ($isFront){
            $newData = $data;
            $data = [];
            foreach ($newData as $key=>$val){
                $data[$key]['id'] = $key;
                $data[$key]['value'] = $val;
            }
        }
        if ($type){
            return $data[$type];
        }else{
            return $data;
        }
    }

    //服务类型
    public static function services($service){
        $data = ['1' => '到店自取', '2' => '送车上门', '3' => '免押金'];
        if($service){
            $service = explode(',', $service);
            $new_data = "";
            foreach ($service as $value){
                if(isset($data[$value])){
                    $new_data .= $data[$value] . ',';
                }
            }
            return rtrim($new_data, ',');
        }else{
            return "";
        }
    }
}
